import { HOME_PATH } from '../pages/pathUrl';
let cacheNavPages = [];

function redirectTo(params = {}) {
    const pathname = params.pathname;
    const queryString = params.queryString !== undefined ? (params.queryString) : '';
    wx.redirectTo({
        url: `${pathname}?${queryString}`,
    });
}
function navigateTo(params = {}) {
    if (!wx) return;
    const pathname = params.pathname;
    let flag;
    getCurrentPages().forEach((page, i) => {
        if (`/${page.__route__}`.indexOf(HOME_PATH) > -1) {
            if (i !== 0) {
                const queryString = params.queryString !== undefined ? (params.queryString) : '';
                wx.redirectTo({
                    url: `${pathname}?${queryString}`,
                });
                flag = true;
            }
        }
    });
    if (flag) return;
    if (getCurrentPages().length < 5) {
        wx.navigateTo({
            url: `${pathname}?${params.queryString}`,
        });
        cacheNavPages = [];// 清空缓存
    } else {
        const lastPage = getCurrentPages()[getCurrentPages().length - 1];
        // 缓存最后的页面信息；
        cacheNavPages.push(lastPage);
        const queryString = params.queryString !== undefined ? (params.queryString) : '';
        // 替换最后一页，跳转到新页
        wx.redirectTo({
            url: `${pathname}?${queryString}`,
        });
    }
}
// delta 返回的页面数
function navigateBack(dept = 1) {
    if (!wx) return;
    // 队列有缓存页面
    if (cacheNavPages.length > 0) {
        if (dept <= cacheNavPages.length) { // 当深度在队列访问内
            const toIndex = cacheNavPages.length - dept;// 定位到要访问的页面，【倒数】
            const page = cacheNavPages[toIndex];
            wx.redirectTo({
                url: `/${page.route}`,
            });
            cacheNavPages.splice(toIndex, dept); // 清空大于当前访问页面的缓存
        } else { // 当回退深度在队列访问外
            const wxPopDept = dept - cacheNavPages.length;// 计算出实际wx栈的回退页数
            cacheNavPages = [];// 清空队列
            wx.navigateBack(wxPopDept);
        }
    } else {
        wx.navigateBack(dept);
    }
}

function reLaunch(params = {}) {
    if (!wx) return;
    const pathname = params.pathname;
    const queryString = params.queryString !== undefined ? (params.queryString) : '';
    wx.reLaunch({
        url: `${pathname}?${queryString}`,
    });
}

module.exports = {
    redirectTo,
    navigateTo,
    navigateBack,
    reLaunch,
};
